<template>
  <view class="scrollArea">
    <wd-swiper custom-class="py-4" :list="sku.skuImgs || []" />
    <view class="bg-white px-3 py-2">
      <view class="flex text-red-500 items-center mb-1">
        <view class="text-sm translate-y-2px"> ￥ </view>
        <view class="text-xl font-bold">
          {{ sku.price }}
        </view>
      </view>
      <view class="text-base font-bold leading-[1.2]">
        {{ sku.skuName }}
      </view>
      <view
        v-if="sku.skuDescription"
        class="text-sm text-gray-500 mt-1 leading-[1.2]"
      >
        {{ sku.skuDescription }}
      </view>
      <view class="text-sm mt-1"> 库存：{{ sku.stock }} </view>
    </view>

    <view class="bg-white mt-3 px-3 py-2">
      <view class="font-bold text-base mb-2"> 商品规格 </view>
      <view
        :class="`${
          sku._id === item._id ? 'activeSpec' : ''
        } flex items-center bg-gray-100 rounded-1 mb-1 px-2 py-1`"
        v-for="item in detail.skus"
        @click="sku = item"
      >
        <image
          v-if="item.skuImgs[0]"
          :src="item.skuImgs[0]"
          class="w-40px h-40px"
        ></image>
        <view class="ml-1">
          {{ formatSpec(item.specifications) }}
        </view>
      </view>
    </view>
  </view>
  <view
    class="buyWrapper px-4 pt-2 bg-white fixed bottom-0 w-screen box-border"
  >
    <view class="flex gap-2">
      <wd-button type="warning" custom-class="flex-1" @click="clickAddToCart"
        >加入购物车</wd-button
      >
      <wd-button type="primary" custom-class="flex-1" @click="buy"
        >立即购买</wd-button
      >
    </view>
  </view>
  <wd-toast />
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { getSpu } from "../../api/product";
import { computed, ref } from "vue";
import { caeateOrder } from "../../api/order";
import { useToast } from "wot-design-uni";
import { addToCart } from "@/api/shoppingCart";

const toast = useToast();
const detail = ref({});
const fetchDetail = (id) => {
  getSpu(id).then((res) => {
    detail.value = res.data;
    const priceList = res.data.skus.map((item) => {
      return item.price;
    });
    const minPrice = Math.min(...priceList);
    const minPriceIndex = priceList.findIndex((item) => {
      return item === minPrice;
    });
    sku.value = res.data.skus[minPriceIndex];
  });
};
onLoad((e) => {
  fetchDetail(e.id);
});

const sku = ref({});

const formatSpec = (spec) => {
  // [{颜色: "晴蓝"}, {存储: "32GB 1TB"}]
  // {颜色: "晴蓝",存储: "32GB 1TB"}
  // ["颜色：晴蓝","存储：32GB 1TB"]
  // "颜色：白色 存储：16G+1T"
  let result1 = {};
  spec.forEach((item) => {
    result1 = {
      ...result1,
      ...item,
    };
  });
  const result2 = [];
  for (const key in result1) {
    result2.push(`${key}: ${result1[key]}`);
  }
  const result3 = result2.join(" ");
  return result3;
};
const clickAddToCart = async () => {
  if (sku.value.status !== 1) {
    toast.warning("该商品已下架");
    return;
  }
  if (sku.value.stock <= 0) {
    toast.warning("该商品已售罄");
    return;
  }
  await addToCart(sku.value._id);
  toast.success("已加入购物车");
};
const buy = () => {
  if (sku.value.status !== 1) {
    toast.warning("该商品已下架");
    return;
  }
  if (sku.value.stock <= 0) {
    toast.warning("该商品已售罄");
    return;
  }
  caeateOrder({
    skuId: sku.value._id,
    quantity: 1,
  }).then((res) => {
    toast.success("购买成功");
    uni.navigateTo({
      url: `/pages/confirm/confirm?orderNo=${res.data.orderNo}`,
    });
  });
};
</script>

<style>
.activeSpec {
  background-color: #e0f7fa;
}

.buyWrapper {
  padding-bottom: var(--status-bar-height);
}

.scrollArea {
  height: calc(100vh - 36px - 0.16rem - var(--status-bar-height));
  overflow-y: scroll;
}
</style>
